package com.partterns.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * java反射攻击单例模式，嘻嘻
 */
public class SingletonReflectAttack {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //攻击饿汉式单例模式
        Class<?> classType = SingletonObject.class;
        Constructor<?> c = classType.getDeclaredConstructor(null);
        c.setAccessible(true);
        SingletonObject s1=(SingletonObject) c.newInstance();
        SingletonObject s2=SingletonObject.getInstance();
        System.out.println("fuck singleton result:"+(s1==s2));
        //攻击懒汉式+静态内部类单例模式（线程安全）
        Class<?> classType2=SafeSingleton.class;
        Constructor<?> c2=classType2.getDeclaredConstructor(null);
        c2.setAccessible(true);
        SafeSingleton safe1=(SafeSingleton) c2.newInstance();
        //下面这一行将出错，因为已经有一个对象了。
        SafeSingleton safe2=SafeSingleton.getInstance();
        System.out.println("fuck singleton result2:"+(safe1==safe2));

    }
}
